/**
 * RequestUtils数据请求工具类
 */
import http from '@ohos.net.http';
import PreferencesUtil from './PreferencesUtil';
import promptAction from '@ohos.promptAction';
import router from '@ohos.router';
import { PreferencesEnum } from './enmu/PreferencesEnmu';
import config from '../api/Config';


class HttpUtils {
  private baseURL: string = config.baseURL
  private authorization: string = config.authorization

  async get(url: string, extraData?: any) {
    return await this.httpRequest(url, http.RequestMethod.GET, extraData)
  }

  async post(url: string, extraData?: any) {
    console.log(extraData)
    return await this.httpRequest(url, http.RequestMethod.POST, extraData)
  }

  async put(url: string, extraData?: any) {
    return await this.httpRequest(url, http.RequestMethod.PUT, extraData)
  }

  async delete(url: string, extraData?: any) {
    return await this.httpRequest(url, http.RequestMethod.DELETE, extraData)
  }

  async httpRequest(url: string, method: http.RequestMethod, extraData?: any) {
    let httpRequest = http.createHttp()
    let token = await PreferencesUtil.getPreferences(PreferencesEnum.USER_PREFERENCES, PreferencesEnum.TOKEN, "") as string
    //console.error("token:" + token)
    // TODO 测试用token
    //token = this.authorization
    if (token == "" && url != "/login" && url != "/register") {
      promptAction.showToast({
        message: '用户未登录',
        duration: 2000,
        bottom: 50
      });
      router.pushUrl({
        url: "pages/login/login"
      },
        router.RouterMode.Standard,
        err => {
          if (err) {
            console.log("页面跳转错误", `${err}-to:pages/NewsDetail`)
          }
        }
      )
    }
    try {
      let res = await httpRequest.request(
        `${this.baseURL}${url}`,
        {
          method: method,
          header: {
            "Content-Type": "application/json;charset=utf-8",
            "Authorization": token,
          },
          extraData: extraData
        }
      )
      if (res.responseCode == 200) {
        return JSON.parse(res.result.toString())
      } else {
        console.log(`请求失败:[${url}]` + res.result)
      }
    } catch (err) {
      console.log(`请求失败:[${url}]` + err.result)
    } finally {
      httpRequest.destroy()
    }
  }
}

let httpUtils: HttpUtils = new HttpUtils()

export default httpUtils
